package com.zyylr.classroomreservationsystem.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.diegodobelo.expandingview.ExpandingItem;
import com.diegodobelo.expandingview.ExpandingList;
import com.zyylr.classroomreservationsystem.R;
import com.zyylr.classroomreservationsystem.bean.Building;
import com.zyylr.classroomreservationsystem.bean.Classroom;
import com.zyylr.classroomreservationsystem.bean.LoginUser;
import com.zyylr.classroomreservationsystem.bean.Msg;
import com.zyylr.classroomreservationsystem.bean.Reservation;
import com.zyylr.classroomreservationsystem.web.IReservation;
import com.zyylr.classroomreservationsystem.web.RetrofitFactory;

import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * 展示空闲教室的可折叠ListView
 */
public class ShowFreeClassroomActivity extends MyBaseCompatActivity {
    private static final String TAG = "showFreeClassroom";
    private ExpandingList buildingExpandingList, floorExpandingList;
    private List<Building> buildings;
    //从FragmentTimeToClassroom中传来的用户选择的开始时间和结束时间
    private long startTime, endTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_free_classroom);
        buildingExpandingList = findViewById(R.id.expanding_list_main);
        //test3();
        Intent intent = getIntent();
        buildings = (List<Building>) intent.getSerializableExtra("buildings");
        startTime = intent.getLongExtra("start_time", -1);
        endTime = intent.getLongExtra("end_time", -1);

        for (Building building : buildings) {
            //createBuildingItems(building);
            List<Classroom> classrooms = building.getClassrooms();
//            ArrayList<String> classroomNames = new ArrayList<>();

            //有序的hashmap,存放classroom id和name
            LinkedHashMap<Integer, String> classroomNameMap = new LinkedHashMap<>();
            for (Classroom classroom : classrooms) {
                classroomNameMap.put(classroom.getId(), classroom.getName());
            }
            int buildingColorRes, buildingIconRes;
            switch (building.getId()) {
                case 1:
                    buildingColorRes = R.color.blue;
                    buildingIconRes = R.drawable.building_boyuelou;
                    break;
                case 2:
                    buildingColorRes = R.color.green;
                    buildingIconRes = R.drawable.building_yifulou;
                    break;
                case 3:
                    buildingColorRes = R.color.purple;
                    buildingIconRes = R.drawable.building_gongxinglou;
                    break;
                case 4:
                    buildingColorRes = R.color.yellow;
                    buildingIconRes = R.drawable.building_lvzhilou;
                    break;
                default:
                    buildingColorRes = R.color.blue;
                    buildingIconRes = R.drawable.building_boyuelou;
                    break;
            }
            addItem(building.getName(), classroomNameMap, buildingColorRes, buildingIconRes);
        }
    }

    /**
     * 给父item添加子item
     *
     * @param title
     * @param subItems
     * @param colorRes
     * @param iconRes
     */
    private void addItem(String title, LinkedHashMap<Integer, String> subItems, int colorRes, int iconRes) {
        final ExpandingItem item = buildingExpandingList.createNewItem(R.layout.expanding_layout_building);

        if (item != null) {
            item.setIndicatorColorRes(colorRes);
            item.setIndicatorIconRes(iconRes);

            ((TextView) item.findViewById(R.id.tv_building)).setText(title);

            item.createSubItems(subItems.size());
            Iterator it = subItems.entrySet().iterator();

            for (int i = 0; i < item.getSubItemsCount(); i++) {
                final View view = item.getSubItemView(i);
                TextView tv_classroom = view.findViewById(R.id.tv_classroom);
                Map.Entry entry = (Map.Entry) it.next();
                //给textView设置额外的数据，这个数据是classroom的id
                tv_classroom.setTag(entry.getKey());
                tv_classroom.setText((String) entry.getValue());
//                tv_classroom.setId();
                addSubItemClickListener(tv_classroom);
            }
        }
    }

    /**
     * 给教室item添加按键监听
     *
     * @param viewClassroom classroom的view
     */
    private void addSubItemClickListener(TextView viewClassroom) {
        viewClassroom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String classroomName = ((TextView) v).getText().toString();
                Integer classroomId = (Integer) v.getTag();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM.dd HH:mm", Locale.CHINA);
                String start = simpleDateFormat.format(new Date(startTime));
                String end = simpleDateFormat.format(new Date(endTime));
                String time = start + "—" + end;
                Log.d(TAG, "onClick: " + classroomName);
                showConfirmDialog(classroomName, time, classroomId);
            }
        });
    }


    /**
     * 提醒用户，是否确定选择此教室进行预约
     *
     * @param whichClassroom 已选择的教室名
     * @param time           处理好的时间段字符串，如"05.28 10:39—05.28 12:30"
     * @param classroomId    点击的教室的id
     */
    private void showConfirmDialog(String whichClassroom, String time, Integer classroomId) {
        AlertDialog.Builder builder;
        builder = new AlertDialog.Builder(this).setTitle("预约确认")
                .setMessage("确定预约 " + time + " 的" + whichClassroom + "教室？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        handlePositiveButtonClicked(classroomId);
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
        builder.create().show();
    }

    /**
     * 处理对话框的确定按钮点击事件（无法从异步显示的对话框中获悉点击的是哪个button）
     *
     * @param classroomId 点击的教室的id
     */
    private void handlePositiveButtonClicked(Integer classroomId) {
        //TODO:用户未登录
        if (!LoginUser.isLogin()) {
            Toast.makeText(getApplicationContext(), "请登录后重试！", Toast.LENGTH_SHORT).show();
            return;
        }
        Retrofit retrofit = RetrofitFactory.getRetrofit();
        IReservation request = retrofit.create(IReservation.class);
        Reservation reservation = new Reservation(LoginUser.getInstance(), new Classroom(classroomId),
                new Date(), new Date(startTime), new Date(endTime));
        Log.d(TAG, "发给服务器的reservation：" + reservation);
        Call<Msg> msgCall = request.getReservationCall(reservation);
        msgCall.enqueue(new Callback<Msg>() {
            @Override
            public void onResponse(Call<Msg> call, Response<Msg> response) {
                Msg msg = response.body();
                Log.d(TAG, "发起预约申请服务器返回的信息：" + msg);
                if (msg.getCode() == 200) {
                    Toast.makeText(getApplicationContext(), "预约申请失败！", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), "预约申请已提交！", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Msg> call, Throwable t) {
                Toast.makeText(getApplicationContext(), "服务请求错误！", Toast.LENGTH_SHORT).show();
            }
        });

    }

    /**
     * 从教室名中获取楼号，实现方法：取教室名的第一个数字
     *
     * @param classroomName 教室名
     * @return 楼层字符串 1、2、……
     */
    private String getFloor(String classroomName) {
        Pattern pattern = Pattern.compile("[A-Z]?(\\d)");
        Matcher matcher = pattern.matcher(classroomName);
        if (matcher.find()) {
            return matcher.group(1);
        } else return null;
    }
}
